﻿using AutoMapper;
using AutoMapper.Configuration;
using NLog;
using Quartz.Impl;
using System;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Reflection;
using System.ServiceProcess;

namespace IOA.MES.AutoJobs
{
    public partial class Service1 : ServiceBase
    {
        private static Logger logger = LogManager.GetCurrentClassLogger();
        public Service1()
        {
            logger.Info("开始启动AutoJobs服务...");
            InitializeComponent();

            //OnStart(null);
        }

        protected override void OnStart(string[] args)
        {
            //初始化AutoMapper
            InitMapper();
            logger.Info("同步作业启动成功");

            try
            {
                //启动异步作业
                var properties = new NameValueCollection
                {
                    { "quartz.serializer.type", "binary" }
                };
                properties["quartz.plugin.xml.type"] = "Quartz.Plugin.Xml.XMLSchedulingDataProcessorPlugin, Quartz.Plugins";
                properties["quartz.plugin.xml.fileNames"] = $"{Environment.CurrentDirectory}\\quartz_jobs.xml";

                var factory = new StdSchedulerFactory(properties);
                var scheduler = factory.GetScheduler().Result;
                scheduler.Start();
                logger.Info("异步作业启动成功");
            }
            catch (Exception ex)
            {
                logger.Error(ex, $"异步作业启动失败，错误信息：{ex.Message}");
            }

            logger.Info("AutoJobs服务启动成功！");
        }

        private void InitMapper()
        {
            var files = Directory.GetFiles(Environment.CurrentDirectory);
            var dataAccessFiles = files.Where(_ => _.EndsWith(".DataAccess.dll")).ToList();

            var cfg = new MapperConfigurationExpression();
            foreach (var dll in dataAccessFiles)
            {
                try
                {
                    var assembly = Assembly.LoadFrom(dll);
                    var type = assembly.GetType(dll.Substring(dll.LastIndexOf("\\") + 1, dll.Length - dll.LastIndexOf("\\") - 5) + ".MapperConvert");
                    if (type != null)
                    {
                        var obj = Activator.CreateInstance(type);
                        var method = type.GetMethod("InitMapper");
                        method.Invoke(obj, new object[] { cfg });
                    }
                }
                catch (Exception ex)
                {
                    logger.Fatal(ex, $"InitMapper出错：{ex.Message}");
                }
            }
            Mapper.Initialize(cfg);
        }

        protected override void OnStop()
        {
            logger.Info("开始停止AutoJobs服务");

            var scheduler = StdSchedulerFactory.GetDefaultScheduler().Result;
            scheduler.Shutdown();

            logger.Info("AutoJobs服务已停止");
        }
    }
}
